package com.jms.product.web;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jms.common.exception.BizCodeEnum;
import com.jms.common.utils.R;
import com.jms.product.constant.AuthServerConstant;
import com.jms.product.entity.UserAuthEntity;
import com.jms.product.entity.UserBaseEntity;
import com.jms.product.service.UserAuthService;
import com.jms.product.service.UserBaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author Jamison
 * @version 1.0
 * @date 2021/6/11 14:44
 */
@RestController
public class LoginController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private UserBaseService userBaseService;

    @Autowired
    private UserAuthService userAuthService;

    /**
     * 手机号验证码登录
     * @param mobile 手机号
     * @param code 验证码
     * @param httpSession session域
     * @return R
     */
    @PostMapping("/user/login")
    public R login(@RequestParam("mobile") String mobile,
                   @RequestParam("code") String code,
                   HttpSession httpSession,
                   HttpServletResponse response){
        System.out.println(mobile + "_" + code);
        String phonePre = AuthServerConstant.SMS_CODE_CACHE_PREFIX + mobile;
        String redisCode = redisTemplate.opsForValue().get(phonePre);
        if (redisCode == null || !redisCode.split("_")[0].equals(code)){
            return R.error(BizCodeEnum.CODE_OVERDUE_OR_ERROR_EXCEPTION.getCode(),
                    BizCodeEnum.CODE_OVERDUE_OR_ERROR_EXCEPTION.getMsg());
        }

        // 从数据库中获取到用户信息
        UserBaseEntity userBaseEntity = userBaseService.getOne(new QueryWrapper<UserBaseEntity>()
                .eq("user_name", mobile)
                .or().eq("mobile", mobile));
        if (userBaseEntity == null){
            // 用户未注册
            return R.error(BizCodeEnum.USER_NOT_REGISTER.getCode(),
                    BizCodeEnum.USER_NOT_REGISTER.getMsg());
        }
        // 登录成功，在session中保存登录信息
        httpSession.setAttribute(AuthServerConstant.LOGIN_USER, userBaseEntity);
        httpSession.setMaxInactiveInterval(60 * 60);
        //存sessionId的cookie
        Cookie cookieSId = new Cookie("JSESSIONID",httpSession.getId());
        cookieSId.setMaxAge(60 * 60);
        cookieSId.setPath("/");
        cookieSId.setDomain("www.childrenwear.com");
        response.addCookie(cookieSId);
        return R.ok().setData(BizCodeEnum.LOGIN_SUCCESS.getMsg());
    }

    /**
     * 用户名密码登录
     * @param username 用户名
     * @param password 密码
     * @param httpSession session
     * @return R
     */
    @PostMapping("/user/userNameLogin")
    public R userNameLogin(@RequestParam("username") String username,
                           @RequestParam("password") String password,
                           HttpSession httpSession,
                           HttpServletResponse response){

        // 根据username获取到用户
        UserBaseEntity userBaseEntity = userBaseService.getOne(new QueryWrapper<UserBaseEntity>()
                .eq("user_name", username)
                .or().eq("mobile", username)
                .or().eq("nick_name", username));
        if (userBaseEntity != null){
            // 代表已经存在这个用户，接下来就是校验密码
            UserAuthEntity userAuthEntity = userAuthService.getOne(new QueryWrapper<UserAuthEntity>()
                    .eq("uid", userBaseEntity.getUid()));
            if (userAuthEntity != null){
                // 校验用户输入的密码是否正确
                BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
                boolean matches = encoder.matches(password, userAuthEntity.getCertificate());
                if (matches){
                    // 密码正确
                    httpSession.setAttribute(AuthServerConstant.LOGIN_USER, userBaseEntity);
                    httpSession.setMaxInactiveInterval(60 * 60);
                    //存sessionId的cookie
                    Cookie cookieSId = new Cookie("JSESSIONID",httpSession.getId());
                    cookieSId.setMaxAge(60 * 60);
                    cookieSId.setPath("/");
                    cookieSId.setDomain("www.childrenwear.com");
                    response.addCookie(cookieSId);
                    return R.ok().setData(BizCodeEnum.LOGIN_SUCCESS.getMsg());
                }
            }
        }

        return R.error(BizCodeEnum.USERNAME_ERROR_OR_PASSWORD_FAILED.getCode(),
                BizCodeEnum.USERNAME_ERROR_OR_PASSWORD_FAILED.getMsg());
    }


}
